<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="消息标题"
            clearable/>
      </el-form-item>

      <el-form-item label="" prop="pushTimeStr">
        <el-date-picker
            v-model="queryParams.pushTimeStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="推送时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="" prop="pushStatus">
        <el-select v-model="queryParams.pushStatus" placeholder="推送状态" clearable>
          <el-option  v-for="(item,index) in pushStatusList"
                      :key="item.value"
                      :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                   :loading="loading">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['wkomsg:list:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="msgList">
      <el-table-column label="标题" align="center" prop="title" width="95"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="推送方式" align="center" prop="pushType">
        <template slot-scope="scope">
          <dict-tag :options="pushTypeList" :value="scope.row.pushType"/>
        </template>
      </el-table-column>
      <el-table-column label="推送时间" align="center" prop="pushTime"></el-table-column>
      <el-table-column label="推送状态" align="center" prop="pushStatus">
        <template slot-scope="scope">
          <dict-tag :options="pushStatusList" :value="scope.row.pushStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"
                       width="120"
                       class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
              v-hasPermi="['wkomsg:list:preview']">详情</el-button>
          <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['wkomsg:list:edit']">编辑</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body center
               :before-close="handleCancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px"
               :class=" !openIsEdit?'noEidt':'' " v-loading="submitLoading">
        <el-row :gutter="5">
          <el-col :span="24" >
            <el-form-item label="消息信息" class="group-title"></el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-container>
              <el-main class="grop-item-main">
                <el-col :span="24">
                  <el-form-item label="消息标题:" prop="title">
                    <el-input v-model="form.title" :readonly="!openIsEdit"/>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="消息内容" prop="msg">
                    <el-input v-model="form.msg" :readonly="!openIsEdit"
                              type="textarea"
                              :rows="3"/>
                  </el-form-item>
                </el-col>
              </el-main>
            </el-container>
          </el-col>

        </el-row>

        <el-row :gutter="5">
          <el-col :span="24" >
            <el-form-item label="推送管理" class="group-title"></el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-container>
              <el-main class="grop-item-main">
                <el-form-item label="推送方式" prop="pushType">
                  <el-select v-model="form.pushType" :disabled="true">
                    <el-option  v-for="(item,index) in pushTypeList"
                                :key="item.value"
                                :label="item.label" :value="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="推送群体" prop="">
                  <el-button type="primary"
                             plain
                             icon="el-icon-plus"
                             size="mini"
                             @click="handleOpenPush"
                  >
                    <span v-if="openIsEdit">人员选择</span>
                    <span v-if="!openIsEdit">查看人员详情</span>
                  </el-button>
                </el-form-item>
              </el-main>
            </el-container>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" v-if="openIsEdit" @click="onSave('0')" >保 存</el-button>
        <el-button type="primary" :loading="submitLoading" v-if="openIsEdit" @click="onPreSubmit()">提 交</el-button>
        <el-button type="primary" :loading="submitLoading" v-if="isShowPush" @click="onSave('1')">确认推送</el-button>
        <el-button v-if="isShowPush" :loading="submitLoading" @click="onReturn()">上一步</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog :title="titlePushObj" :visible.sync="openPush" width="780px" append-to-body center
               :before-close="handleCancelPush">
      <el-row :gutter="10" >
        <!--部门数据-->
        <el-col :span="6" :xs="24" v-if="openIsEdit">
          <div class="grp_border">
            <div class="head-container grp_title">
              <el-input
                  v-model="pushQueryParams.deptName"
                  placeholder="组织名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
              />
            </div>
            <div class="head-container grp_content" >
              <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  @node-click="handleNodeClick"
              />
            </div>
          </div>

        </el-col>

        <!--用户数据-->
        <el-col :span="9" :xs="24" v-if="openIsEdit">
          <div class="grp_border">
            <div class="head-container grp_title">
              <el-input
                  v-model="pushQueryParams.userName"
                  placeholder="登陆名"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
              />
            </div>
            <div class="head-container grp_content" >
              <el-table v-loading="pushUserloading" :data="userList" @selection-change="handleUserSelChange">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="登陆名" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
                <el-table-column label="姓名" align="center" key="realName" prop="realName" :show-overflow-tooltip="true" />
              </el-table>
              <pagination
                  v-show="userTotal>0"
                  :total="userTotal"
                  :page.sync="pushQueryParams.pageNum"
                  :limit.sync="pushQueryParams.pageSize"
                  @pagination="getUserList"
              />
            </div>
          </div>
        </el-col>


        <!--选择数据-->
        <el-col :span="9" :xs="24"  class="grp_border">
          <div class="head-container grp_title">
            <div style="float:left;">已选 {{userPushList.length}}</div>
            <div style="float:right" v-if="openIsEdit">
              <el-button
                type="text"
                size="small"
                icon="el-icon-delete"
                @click="handleClearPushUser()">清空</el-button>
            </div>
          </div>
          <div class="head-container grp_content" >
            <el-table  :data="userPushList">
              <el-table-column label="姓名" align="center" key="realName" prop="realName" :show-overflow-tooltip="true" />
              <el-table-column label="操作" align="center"
                               class-name="small-padding fixed-width" fixed="right" v-if="openIsEdit">
                <template slot-scope="scope">
                  <el-button
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      @click="handleRemovePushUser(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="openIsEdit" @click="onSavePushUser()">确 定</el-button>
        <el-button v-if="openIsEdit" @click="handleCancelPush">取 消</el-button>
        <el-button v-if="!openIsEdit" @click="handleClosePush">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import "@/style/customer.scss";
  import {listMsg,saveMsg,pushMsg,getMsgById} from "@/api/wkomsg/wkomsg.js";
  import { listUser,deptTreeSelect } from "@/api/system/user";


  export default {
    name: "Wkomsg_list",
    data(){
      return {
        // 显示搜索条件
        showSearch: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title:undefined,
          pushTimeStr:undefined,
          pushStatus:undefined
        },
        // 总条数
        total: 0,
        pushStatusList:[
          {
            raw:{
              listClass:"default",
              cssClass:""
            },
            value:"PEND",
            label:"待推送"
          },
          {
            raw:{
              listClass:"default",
              cssClass:""
            },
            value:"SENT",
            label:"已推送"
          },
        ],
        loading:false,
        // 表格数据
        msgList: [],
        pushTypeList:[
          {
            raw:{
              listClass:"default",
              cssClass:""
            },
            value:"IM",
            label:"站内信"
          },

          {
            raw:{
              listClass:"default",
              cssClass:""
            },
            value:"SN",
            label:"服务号"
          },

          {
            raw:{
              listClass:"default",
              cssClass:""
            },
            value:"APP",
            label:"APP"
          },
        ],
        submitLoading:false,
        open:false,
        openIsEdit:false,
        isShowPush:false,//推送 按钮展示
        form:{
          pkId:undefined,
          title:undefined,
          msg:undefined,
          pushType:'IM',
          recvList:[]
        },
        rules:{},
        openPush:false,
        // 部门树选项
        deptOptions: undefined,
        defaultProps: {
          children: "children",
          label: "label"
        },
        pushQueryParams:{
          deptName:undefined,//推送部门查询
          deptId:undefined,
          pageNum:1,
          pageSize: 10,
          userName:undefined,
          excludeUserIds:[1]
        },
        pushUserloading:false,
        userList: null,//查询的用户数据
        userTotal:0,
        userPushList:[],//pkId，realName
        uesrIds:[],//选中的user
        titlePushObj:"推送对象",

      }
    },
    created(){
      this.getList();
    },
    watch: {
      // 根据名称筛选部门树
      /*pushQueryParamsDeptName(val) {
        this.$refs.tree.filter(val);
      }*/
      "pushQueryParams.deptName": function (newValue, oldValue) {
        // 这里编写你对变化的响应逻辑
        //console.log(`someProperty changed from ${oldValue} to ${newValue}`);
        this.$refs.tree.filter(newValue);
      }
    },
    methods:{
      getList(){
        this.loading = true;
        listMsg(this.queryParams).then( (res)=>{
          this.msgList = res.data;
          this.total = Number(res.total);
        }).finally(()=>{
          this.loading = false;
          //放在list查询之后，防止并发执行

        });;
      },

      resetQuery() {
        this.resetForm("queryForm");
        //this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      handleAdd(){
        this.reset();
        this.open = true;
        this.openIsEdit=true;
        this.title = "新增";
      },
      // 表单重置
      reset() {
        this.form = this.$options.data().form
        this.resetForm("form");
      },
      handleCancel(){
        this.open=false;
        this.openIsEdit=false;
        this.isShowPush=false;
        this.reset();
        this.handleCancelPush();
      },

      handleOpenPush(){
        if(!this.deptOptions){
          this.getDeptTree();
        }

        this.openPush=true;
      },
      handleCancelPush(){
        this.handleClosePush()
        this.pushQueryParams=this.$options.data().pushQueryParams
        this.userList=[];
        this.userPushList=[];
      },
      handleClosePush(){
        this.openPush=false;
      },

      getDeptTree() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      handleNodeClick(data) {
        this.pushQueryParams.deptId = data.id;
        this.onQueryUser();
      },
      onQueryUser(){
        this.pushQueryParams.pageNum = 1;
        this.getUserList();
      },
      getUserList() {
        this.pushUserloading = true;
        listUser(this.addDateRange(this.pushQueryParams, undefined)).then(response => {
              this.userList = response.data;
              this.userTotal = Number(response.total);
              this.pushUserloading = false;
            }
        );
      },
      handleUserSelChange(selection) {
        debugger;
        this.uesrIds = selection.map(item => item.pkId);
        let addWay="0"//添加方式 1 从前往后  0= 从后往前
        if(this.userPushList.length==0){
          addWay="1";
        }

        for(let i=0;i<selection.length;i++) {
          for(let u=this.userPushList.length-1;u>=0;u--){
            if(this.userPushList[u].pkId == selection[i].pkId){
              this.userPushList.splice(u,1)
            }
          }
          if(addWay=="0"){
            this.userPushList.unshift(selection[i]);//有数据 添加到第一
          }else{
            this.userPushList.push(selection[i]);// 无数据 按顺序添加
          }

        }

      },
      handleRemovePushUser(row){
        debugger;
        for(let i=0;i<this.userPushList.length;i++){
          if(this.userPushList[i].pkId==row.pkId){
            this.userPushList.splice(i,1)
          }
        }
      },
      handleClearPushUser(){
        this.userPushList=[]
      },
      onSavePushUser(){
        this.openPush=false;
      },

      //isPush 0 不推送，1 推送
      onSave(isPush){

        this.submitLoading=true;
        this.form.recvList=[];
        for(let i=0;i<this.userPushList.length;i++){
          let obj={
            recvId:this.userPushList[i].pkId,
            recvRealName:this.userPushList[i].realName
          }
          this.form.recvList.push(obj);
        }

        if(isPush=="0"){//不推送
          saveMsg(this.form).then ((res)=>{
            this.$alert("操作成功");
            this.handleCancel();
            this.handleQuery();
          }).finally(() =>{
            this.submitLoading=false;
          });
        }else{
          pushMsg(this.form).then ((res)=>{
            this.$alert("操作成功");
            this.handleCancel();
            this.handleQuery();
          }).finally(() =>{
            this.submitLoading=false;
          });
        }

      },
      onPreSubmit(){
        this.openIsEdit=false;
        this.isShowPush=true;
      },
      onReturn(){
        this.openIsEdit=true;
        this.isShowPush=false;
      },

      handlePreview(row){
        this.openIsEdit=false;
        this.getFormData(row);
      },
      handleEdit(row){
        this.openIsEdit=true;
        this.getFormData(row);
      },
      getFormData(row){
        const pkId=row.pkId;
        getMsgById(pkId).then( (res)=>{
          this.form = res.data;
          this.userPushList=[];
          let recvList=this.form.recvList;
          for(let i=0; i<recvList.length; i++){
            let obj={
              pkId:recvList[i].recvId,
              realName:recvList[i].recvRealName,
            }
            this.userPushList.push(obj);
          }
          debugger;

          this.open = true;
          this.title = "详情";
        });
      }
    },
  }
</script>

<style lang="scss" scoped>
  .grp_border{
    border:1px solid #eee;
    padding: 5px;
  }
  .grp_content{
    height:400px;
    overflow:auto;
  }

  .grp_title{
    height: 50px;
    //margin-bottom: 20px
  }

</style>
